package com.zry.yard.ui.activity.map

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import com.baidu.location.*

import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.search.geocode.*

import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @author 19428
 */
class BaiDuService : Service(), OnGetGeoCoderResultListener {


    private var locationBean: BDLocation? = null
    // 定位相关
    private var mLocClient: LocationClient? = null
    var myListener = MyLocationListenner()
    private var mCurrentLat = 0.0
    private var mCurrentLon = 0.0


    /**
     * 通过binder实现了 调用者（client）与 service之间的通信
     */


    private val binder = MyBinder()

    inner class MyBinder : Binder() {

        val service: BaiDuService
            get() = this@BaiDuService
    }


    override fun onCreate() {
        EventBus.getDefault().register(this)
        super.onCreate()
    }

    override fun onBind(intent: Intent): IBinder? {
        startLocation()
        return binder
    }


    private fun startLocation() {
        // 定位初始化
        mLocClient = LocationClient(this)
        mLocClient!!.registerLocationListener(myListener)
        val option = LocationClientOption()
        option.locationMode = LocationClientOption.LocationMode.Hight_Accuracy
        // 设置坐标类型
        option.setCoorType("bd09ll")
        option.setScanSpan(1000)
        // 打开gps
        option.isOpenGps = true
        option.setIsNeedAddress(true)
        mLocClient!!.locOption = option
        mLocClient!!.start()


    }

    /**
     * 定位SDK监听函数
     */
    inner class MyLocationListenner : BDAbstractLocationListener() {

        override fun onReceiveLocation(location: BDLocation) {
            locationBean = location
            Log.e("locationBean", location.toString())

            if (location.latitude != 0.0 && location.longitude != 0.0) {
                EventBus.getDefault().post(locationBean)
            }
        }
    }


    //根据位置查找经纬度
    override fun onGetGeoCodeResult(geoCodeResult: GeoCodeResult?) {

    }

    //根据经纬度查找位置
    override fun onGetReverseGeoCodeResult(reverseGeoCodeResult: ReverseGeoCodeResult?) {

    }


    @Subscribe(threadMode = ThreadMode.POSTING)
    fun onMoonEvent(stopClient: StopClient) {
        if (stopClient.stopStr == "获取到了地址") {
            mLocClient!!.stop()
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        // 退出时销毁定位
        mLocClient!!.stop()
        EventBus.getDefault().unregister(this)
    }
}
